package com.feicheng.iou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.iou.commom.ReturnCode;
import com.feicheng.iou.entity.Permission;
import com.feicheng.iou.entity.RolePermission;
import com.feicheng.iou.entity.User;
import com.feicheng.iou.entity.UserRole;
import com.feicheng.iou.exception.SystemException;
import com.feicheng.iou.mapper.PermissionMapper;
import com.feicheng.iou.mapper.RolePermissionMapper;
import com.feicheng.iou.mapper.UserMapper;
import com.feicheng.iou.mapper.UserRoleMapper;
import com.feicheng.iou.pojo.login.UserPOJO;
import com.feicheng.iou.pojo.login.LoginParamPOJO;
import com.feicheng.iou.pojo.login.UserPagePOJO;
import com.feicheng.iou.pojo.login.UserRolePOJO;
import com.feicheng.iou.result.ResultInfo;
import com.feicheng.iou.result.ResultInfoV110;
import com.feicheng.iou.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianchunlei
 * @since 2021-06-28
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserRolePOJO userRolePOJO;

    @Autowired
    private UserPagePOJO userPagePOJO;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * @param loginParamPOJO
     * @return ResultInfo
     * @Author wuweinan
     * @Description 登录验证与权限接口, 查询用户信息
     * @Date 2021-7-23 10:45
     */
    @Override
    public User selectUserInfoOfLogin(LoginParamPOJO loginParamPOJO) {
        log.info("UserServiceImpl的selectUserInfoOfLogin方法进入，参数loginParamPOJO：" + loginParamPOJO);
        User user = userMapper.selectUserInfoOfLogin(loginParamPOJO);
        //校验用户名和密码是否正确
        if (user == null) {
            throw new SystemException(ReturnCode.ACCOUNT_PASSWORD_WRONG);
        }
        return user;
    }


    /**
     * @param userPOJO
     * @return ResultInfo
     * @Author wuweinan
     * @Description //新增用户信息及其权限
     * @Date 2021-7-23 10:45
     */
    @Override
    @Transactional
    public ResultInfo AddUser(UserPOJO userPOJO) {
        log.info("UserServiceImpl的AddUser方法进入，参数loginParamPOJO：" + userPOJO);
        //新增用户
        Integer integer = userMapper.insertUser(userPOJO);

        if (integer != 1) {
            throw new SystemException(ReturnCode.ADD_USER_FAIL);
        }

        //新增多条用户与角色中间表
        Integer integer1 = userRoleMapper.insertUserRoleByUserId(userPOJO.getUser().getUserId(),
                userPOJO.getRoleIds());

        if (integer1 == 0) {
            throw new SystemException(ReturnCode.INSERT_ROLE_FAIL);
        }


        return ResultInfo.success();
    }

    /**
     * @param name
     * @return ResultInfo
     * @Author wuweinan
     * @Description //模糊查询用户
     * @Date 2021-7-23 10:45
     */
    @Override
    public ResultInfo queryUserListByCondition(String name) {
        log.info("UserServiceImpl的AddUser方法进入，参数name：" + name);
        List<User> users = userMapper.selectUserListByCondition(name);

        return ResultInfo.success(users);
    }

    /**
     * @param userPOJO
     * @return ResultInfo
     * @Author wuweinan
     * @Description //更改用户的权限和信息
     * @Date 2021-7-23 10:45
     */
    @Override
    public ResultInfo updateUserMessage(UserPOJO userPOJO) {
        log.info("UserServiceImpl的updateUserMessage方法进入，参数userPOJO：" + userPOJO);
        userPOJO.getUser().setUt(LocalDateTime.now());
        //更新用户信息
        int i = userMapper.updateById(userPOJO.getUser());
        if (i != 1) {
            //更新用户信息失败
            throw new SystemException(ReturnCode.UPDATE_USER_FAIL);
        }

        //删除用户对应的所有角色
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userPOJO.getUser().getUserId());
        int delete = userRoleMapper.delete(queryWrapper);

        if (delete == 0) {
            //删除用户角色失败
            throw new SystemException(ReturnCode.DELETE_ROLE_FAIL);
        }

        //插入新的角色
        Integer integer = userRoleMapper.insertUserRoleByUserId(userPOJO.getUser().getUserId(),
                userPOJO.getRoleIds());

        if (integer == 0) {
            //插入角色失败
            throw new SystemException(ReturnCode.INSERT_ROLE_FAIL);
        }


        return ResultInfo.success();
    }

    /**
     * @param name
     * @return ResultInfo
     * @Author wuweinan
     * @Description //判断用户名是否存在
     * @Date 2021-7-23 10:45
     */
    @Override
    public ResultInfo judgeUserAccount(String name) {
        Integer integer = userMapper.judgeAccountName(name);
        if (integer != 0) {
            throw new SystemException(ReturnCode.ACCOUNT_DUPLICATE);
        }

        return ResultInfo.success("用户名可用");
    }


    /**
     * @Author wuweinan
     * @Description //查询所有市场管理用户
     * @Date 2021-7-23 10:45
     * @param page , size
     * @return  ResultInfo
     */
    @Override
    public ResultInfo selectAllMarketUser(Integer page,Integer size) {
        //查询出所有用户
        List<User> users = userMapper.selectAllUser(page,size);
        //所有市场用户
        List<User> marketUsers = new ArrayList<>();
        //if(user有市场管理权限的话)    根据user_id查询role_ids   根据roleIds查询permissions 是否有市场管理
        //userIds集合
        //遍历users
        //判断这个用户是否有"市场管理权限"
        for (User user : users) { //for outside

            Integer marketPermissionCount = 0;
            //根据userId获取对应的roleIds
            List<Integer> roleIdList = userRoleMapper.selectRoleIds(user.getUserId());
            //如果用户没有角色就跳出本次循环
            if(roleIdList.size() == 0){
                continue;
            }
            //根据rouIdList获取对应的PermissonIds
            List<Integer> permissionIds = rolePermissionMapper.selectUserPermission(roleIdList);
            //如果角色没有权限
            if(permissionIds.size() == 0){
                continue;
            }
            //遍历permissions查看是否有"市场管理权限"
            for (Integer permissionId : permissionIds) {

                if(permissionMapper.selectById(permissionId).getName().equals("咨询管理")){
                    marketPermissionCount++;
                }
            }
            //计数器 大于等于一的话 就是有"市场管理权限"
            if(marketPermissionCount >= 1){
                marketUsers.add(user);
            }
        } //for outside

        //不需要分页  直接返回市场人员
        userPagePOJO.setUserList(marketUsers);
        return  ResultInfo.success(userPagePOJO);

    }


    /**
     * @Author wuweinan
     * @Description //查询所有用户
     * @Date 2021-7-23 10:45
     * @param page , size
     * @return  ResultInfo
     */
    @Override
    public ResultInfoV110 selectAllUser(Integer page, Integer size) {
        log.info("UserServiceImpl的selectAllUser方法进入,参数page为"+page+",参数size为"+size);
        //查询出多少用户
        List<User> users = userMapper.selectAllUser(page,size);

        //设置分页信息
        Integer count = users.size();
        userPagePOJO.setPage(page);
        userPagePOJO.setSize(size);
        userPagePOJO.setTotalCount(count);

        //计算总页数，将double转化成int
        Double doubleCount = (double)count/size;
        double ceil = Math.ceil(doubleCount);
        int totolPage = (int)ceil;
        userPagePOJO.setTotalPage(totolPage);
        userPagePOJO.setUserList(users);

        return ResultInfoV110.success(userPagePOJO);
    }

    /**
     * @param userId
     * @return ResultInfo
     * @Author wuweinan
     * @Description //根据用户Id查询用户
     * @Date 2021-7-23 10:45
     */
    @Override
    public ResultInfo selectUserById(Integer userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        User user = userMapper.selectOne(queryWrapper);

        QueryWrapper<UserRole> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", userId);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper1);

        userRolePOJO.setUser(user);
        userRolePOJO.setUserRoleList(userRoles);


        return ResultInfo.success(userRolePOJO);
    }
}
